﻿using Newtonsoft.Json;
using System.Linq;

namespace HamcoWcs.Models.DeviceMsgs
{
    public abstract class MsgBase
    {
        public MsgBase(bool isReserve = true)
        {
            IsReserve = isReserve;
        }

        public bool IsReserve { get; set; }

        protected ushort Reserve(ushort Num)
        {
            return IsReserve ? (ushort)((Num & 0xFF) << 8 | Num >> 8) : Num;
        }



        /// <summary>
        /// 根据IsReserve判断是否要反转数据
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        protected byte[] Reserve(byte[] bytes)
        {
            return IsReserve ? bytes.Reverse().ToArray() : bytes;
        }

        /// <summary>
        /// 获取bytes中片段
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="startPosition"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        protected byte[] GetBytes(byte[] msg, int startPosition, int length)
        {
            var bytes = msg.Skip(startPosition).Take(length);
            bytes = IsReserve ? bytes.Reverse() : bytes;
            return bytes.ToArray();
        }

        /// <summary>格式化自身位Json字符串 </summary>
        public string ToJson()
            => JsonConvert.SerializeObject(this);
    }
}
